package com.dream21th.dream21thredis.handler;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.alibaba.fastjson.JSONObject;
import com.dream21th.dream21thredis.annotation.Encode;
import com.dream21th.dream21thredis.exception.FlowException;
import com.dream21th.dream21thredis.util.HttpUtils;
import com.dream21th.dream21thredis.util.IpUtils;
import com.dream21th.dream21thredis.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
/**
 * https://www.cnblogs.com/EasonJim/p/7727012.html
 * https://www.cnblogs.com/EasonJim/p/7704740.html
 * 
 *
 */
@Slf4j
public class EncodeHandler extends HandlerInterceptorAdapter {
	
	private RestTemplate restTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler){
       log.info("--------------------------------preHandle");
       Encode encodeMethod= ((HandlerMethod) handler).getMethodAnnotation(Encode.class);              //方法注解
       Encode encodeClass= ((HandlerMethod) handler).getBean().getClass().getAnnotation(Encode.class);      //类注解
       boolean vcode = true;
       String ip=IpUtils.getIpAddr(request);
       restTemplate=SpringUtil.getBean("restTemplate");
      /* Map<String,String> map=new HashMap<>();
       map.put("ip", ip);
       restTemplate.postForObject("http://ip.taobao.com/service/getIpInfo.php", map, JSONObject.class);*/
       String address=getRealAddressByIP(ip);
       if(encodeMethod!= null){
          
       }else if(encodeClass!= null){
         
       }else{
    	   //throw new FlowException("123456");
       }
       return vcode;
    }
  
    public String getRealAddressByIP(String ip)
    {
        String address = "";
        try
        {
            address = HttpUtils.sendPost("http://ip.taobao.com/service/getIpInfo.php", "ip=" + ip);
            JSONObject json = JSONObject.parseObject(address);
            JSONObject object = json.getObject("data", JSONObject.class);
            String region = object.getString("region");
            String city = object.getString("city");
            address = region + " " + city;
        }
        catch (Exception e)
        {
            log.error("根据IP获取所在位置----------错误消息：" + e.getMessage());
        }
        return address;
    }
}

